package br.megareleased.rss;

import java.util.Set;

import org.appwork.utils.event.Eventsender;

import br.megareleased.GetLink;
import br.megareleased.model.Episode;
import br.megareleased.rss.parser.Feed;
import br.megareleased.rss.parser.FeedMessage;
import br.megareleased.rss.parser.RSSFeedParser;
import br.megareleased.tvshow.SerieController;

class RSSVerifierControllerBroadcaster extends Eventsender<RSSVerifierControllerListener, RSSVerifierControllerEvent> {

    @Override
    protected void fireEvent(final RSSVerifierControllerListener listener, final RSSVerifierControllerEvent event) {
        listener.onRSSVerifierControllerEvent(event);
    }
}

public class RSSVerifierController implements RSSVerifierControllerListener, RSSVerifierControllerInterface {

	private transient RSSVerifierControllerBroadcaster broadcaster = new RSSVerifierControllerBroadcaster();
    private static RSSVerifierController INSTANCE = new RSSVerifierController();
    
    public static RSSVerifierController getInstance() {
        return INSTANCE;
    }
	
    private RSSVerifierController() {
        broadcaster.addListener(this);
    }

    public void addListener(final RSSVerifierControllerListener l) {
        broadcaster.addListener(l);
    }

    public void removeListener(final RSSVerifierControllerListener l) {
        broadcaster.removeListener(l);
    }
    
	@Override
	public void onRSSVerifierControllerEvent(RSSVerifierControllerEvent event) {
	}

	@Override
	public void execute() {
		Set<RSS> rssList = RSSController.getInstance().getRSS();
		broadcaster.fireEvent(new RSSVerifierControllerEvent(this, RSSVerifierControllerEvent.VERIFI, rssList));

		for (RSS rss : rssList) {
			RSSFeedParser parser = new RSSFeedParser(rss.getUrl());
			Feed feed = parser.readFeed();
			for (FeedMessage message : feed.getMessages()) {
				SerieController.getInstance().parse(message.getTitle());
			}
		}
	}

}
